﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using BookStoreService.Core.Tools;

namespace BookStoreService.Core.Repository
{
    public class BoCollectionToFileRepository<T> : IRepository<T> where T : class
    {
        private readonly string m_fileFullPath;
        private readonly List<T> m_list;

        public BoCollectionToFileRepository(string fileFullPath)
        {
            m_fileFullPath = fileFullPath;
            if (File.Exists(m_fileFullPath))
            {
                m_list = FilePersistence.Load<T>(m_fileFullPath);
            }
            else
            {
                m_list = new List<T>();
            }
        }

        #region IRepository<T> Members

        public IQueryable<T> Query()
        {
            var users = new EnumerableQuery<T>(m_list);

            return users;
        }

        public void Add(T entity)
        {
            m_list.Add(entity);
        }

        public void Remove(T entity)
        {
            m_list.Remove(entity);
        }

        public void Attach(T current, T original)
        {
        }

        public void Attach(T current)
        {
        }

        public void SubmitChanges()
        {
            FilePersistence.Save(m_list, m_fileFullPath);
        }

        #endregion   
    }
}
